package hang.xipujewelWeb.service.account;

import hang.xipujewelWeb.entity.account.User;
import hang.xipujewelWeb.entity.app.ExchangeRate;
import hang.xipujewelWeb.entity.app.Jewel;
import hang.xipujewelWeb.repository.jpa.JewelDao;
import hang.xipujewelWeb.service.common.JpaManager;

import java.util.List;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户管理类.
 * 
 * @author qizai
 */
@Component
@Transactional
public class JewelManager extends JpaManager<Jewel, JewelDao> {

	private static Logger logger = LoggerFactory.getLogger(JewelManager.class);

	@Autowired
	private JewelDao jewelDao;

	@Autowired
	private ExchangeRateManager exchangeRateManager;

	@Transactional(readOnly = false)
	public void deleteAll() {
		Session session = (Session) entityManager.getDelegate();
		String deleteOrderJewel = "delete from order_jewel";
		session.createSQLQuery(deleteOrderJewel).executeUpdate();
		String deleteShopCart = "delete from ShoppingCart";
		session.createQuery(deleteShopCart).executeUpdate();
		jewelDao.deleteAll();
	}

	@Transactional(readOnly = false)
	public void delete(Long id) {
		Session session = (Session) entityManager.getDelegate();
		String deleteOrderJewel = "delete from order_jewel oj where oj.jewel_id=" + id;
		session.createSQLQuery(deleteOrderJewel).executeUpdate();
		String deleteShopCart = "delete from ShoppingCart sc where sc.jewel.id=" + id;
		session.createQuery(deleteShopCart).executeUpdate();
		jewelDao.delete(id);
	}

	public List<Jewel> list(String shape, String color, String neatness, String cut, String buffing, String symmetry,
			String fluorescence, String card, String site, float startWeight, float endWeight, int startPrice,
			int endPrice, String top, int page, User cuser, String order, String num, String cardId, String holdType) {

		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		float rate = exchangeRate.getRate();
		float userDiscout = cuser.getParent().getPriceBaseNumber().getJewelBaseNumBer();
		Session session = (Session) entityManager.getDelegate();
		String orderBy = "";
		String sql = "From Jewel where id!=0 and isBuy!=1 ";

		if (shape != null && !"".equals(shape.trim())) {
			if (shape.contains("其他")) {
				String notInShape = initNotInShape(shape);
				if (notInShape != null && !"".equals(notInShape)) {
					sql += " and (shape not  in(" + paraFormat(notInShape) + ")";
				}
				if ("其他".equals(shape.trim())) {
					sql += ")";
				} else if (!"其他".equals(shape.trim())) {
					shape = shape.replace(" ", "").replace(",其他", "");
					sql += " or shape in(" + paraFormat(shape) + ") )";
				}
			} else {
				if (!"其他".equals(shape.trim())) {
					shape = shape.replace(" ", "").replace(",其他", "");
					sql += " and shape in(" + paraFormat(shape) + ") ";
				}
			}

		}

		if (color != null && !"".equals(color)) {
			sql += " and color in(" + paraFormat(color.toUpperCase()) + ")";
		}
		if (neatness != null && !"".equals(neatness)) {
			sql += " and neatness in(" + paraFormat(neatness.toUpperCase()) + ")";
		}
		if (buffing != null && !"".equals(buffing)) {
			sql += " and buffing in(" + paraFormat(buffing.toUpperCase()) + ")";
		}
		if (symmetry != null && !"".equals(symmetry)) {
			sql += " and symmetry in(" + paraFormat(symmetry.toUpperCase()) + ")";
		}
		if (fluorescence != null && !"".equals(fluorescence)) {
			sql += " and fluorescence in(" + paraFormat(fluorescence.toUpperCase()) + ")";
		}
		if (card != null && !"".equals(card)) {
			sql += " and card in(" + paraFormat(card.toUpperCase()) + ")";
		}
		if (cut != null && !"".equals(cut)) {
			sql += " and cut in(" + paraFormat(cut.toUpperCase()) + ")";
		}
		if (num != null && !"".equals(num)) {
			sql += " and num in(" + paraFormat(num.toUpperCase()) + ")";
		}
		if (cardId != null && !"".equals(cardId)) {
			sql += " and cardId in(" + paraFormat(cardId.toUpperCase()) + ")";
		}
		if (holdType != null && !"".equals(holdType)) {
			sql += " and holdType in(" + paraFormat(holdType.toUpperCase()) + ")";
		}
		sql += "  and weight >= " + (startWeight - 0.0001) + " and weight <= " + (endWeight + 0.0001)
				+ " and internationalPrice*weight*(1+(discount+" + userDiscout + ")/100)*" + rate + " >= " + startPrice
				+ " and internationalPrice*weight*(1+(discount+" + userDiscout + ")/100)*" + rate + "<= " + endPrice
				+ "  ";
		if (order != null && !"".equals(order)) {
			order = order.trim();
			if ("折扣从高到低".equals(order)) {
				orderBy = "order by discount asc";
			} else if ("折扣从低到高".equals(order)) {
				orderBy = "order by discount desc";
			} else if ("价格从高到低".equals(order)) {
				orderBy = "order by (internationalPrice*weight*(1+(discount+" + userDiscout + ")/100)*" + rate
						+ ") desc";
			} else if ("价格从低到高".equals(order)) {
				orderBy = "order by (internationalPrice*weight*(1+(discount+" + userDiscout + ")/100)*" + rate
						+ ") asc";
			}
		} else {
			orderBy = " order by discount asc ";
		}
		sql += " " + orderBy;
		System.out.println("查询钻石的" + sql);
		if (page != -1)
			return session.createQuery(sql).setFirstResult((page) * 20).setMaxResults(20).list();
		else
			return session.createQuery(sql).list();
	}

	public int count() {
		Session session = (Session) entityManager.getDelegate();
		String sql = "select count(*) from Jewel where isBuy!=1";
		Long count = (Long) session.createQuery(sql).uniqueResult();
		return count.intValue();
	}

	private String paraFormat(String para) {
		String value = "";
		String[] subParas = para.split(",");
		for (int j = 0; j < subParas.length; j++) {
			value += "'" + subParas[j].trim() + "',";
		}
		return value.substring(0, value.length() - 1);
	}

	private String initNotInShape(String paraShape) {
		String[] allShapes = { "圆形", "公主方", "梨形", "心形", "橄榄", "椭圆形", "祖母绿", "其他" };
		String[] paraShapes = paraShape.split(",");
		String notInShape = "";
		for (String s : allShapes) {
			int i = 0;
			for (String ps : paraShapes) {
				if (!s.equals(ps.trim())) {
					i++;
				} else {
					break;
				}
			}
			if (i == paraShapes.length && !"其他".equals(s.trim())) {
				notInShape = notInShape + s + ",";
			}
		}
		return notInShape.substring(0, notInShape.length() - 1);
	}

	@Override
	protected JewelDao getDao() {
		return jewelDao;
	}
}
